package com.kandinfo.isbnmanage.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.kandinfo.base.common.util.PropertiesParse;

/**
 * 阿里云OSS文件上传处理
 * @author weiwang
 */
@Service
public class AliyunOSSUtil {
	
	private String accessKeyId;
	private String accessKeySecret;
	private String endpoint;
	private String bucketName;
	
	private OSSClient client = null;
	private ObjectMetadata meta = null;
	
	public AliyunOSSUtil(){
		Map<String, Object> maps = PropertiesParse.properties2Map("env/env-var.properties");
		accessKeyId = (String)maps.get("accessKeyId");
		accessKeySecret = (String)maps.get("accessKeySecret");
		endpoint = (String)maps.get("endpoint");
		bucketName = (String)maps.get("bucketName");
		
		client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		meta = new ObjectMetadata();
		System.out.println("AliyunOSSUtil初始化完毕!");
	}
	
	public String getKeyFromUrl(String url){
		return url.replace("http://" + bucketName + "." + endpoint + "/", "");
	}
	
	/**
	 * 文件复制
	 * @param sourcePath
	 * @param targetPath
	 */
	public void copyAllObject(String sourcePath,String targetPath){
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
		listObjectsRequest.setPrefix(sourcePath);
		listObjectsRequest.setMaxKeys(1000);
		ObjectListing o;
		String marker = null;
		do{
			listObjectsRequest.setMarker(marker);
			o = client.listObjects(listObjectsRequest);
			// 遍历所有Object
		    for (OSSObjectSummary objectSummary : o.getObjectSummaries()) {
		    	String key = objectSummary.getKey();
		    	if(!key.endsWith("/")){//表示是文件
		    		copyObject(key,key.replace(sourcePath, targetPath));
		    	}
		    }
		    marker = o.getNextMarker();
		}while(o.getNextMarker()!=null);
	}
	
	/**
	 * 判断一个字符串是否全是数字
	 * @param str
	 * @return
	 */
	public boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public String uploadFile(InputStream input, String fileName, String directory) throws IOException {
		meta.setContentLength(input.available());
		meta.setContentType(contentType(fileName));
		// 给文件名加上时间
		String key = System.currentTimeMillis() + "@" + fileName;
		// 上传Object
		client.putObject(bucketName, directory + "/" + key, input, meta);
		return key;
	}

	public String getUrl(String key) {
		return "http://" + bucketName + "." + endpoint + "/" + key;
	}
	
	/**
	 * 附件复制,同一个bucketName之间复制
	 * @param sourceKey
	 * @param destinationKey
	 */
	public void copyObject(String sourceKey,String destinationKey){
		client.copyObject(bucketName, sourceKey, bucketName, destinationKey);
	}
	
	/**
	 * 删除文件
	 * 
	 * @param key
	 */
	public void deleteFile(String key) {
		client.deleteObject(bucketName, key);
	}

	/**
	 * 根据文件类型设置contentType
	 *
	 * @param fileName
	 * @return
	 */
	private String contentType(String fileName) {
		if (fileName.endsWith("xml")) {
			return "text/xml";
		} else if (fileName.endsWith("jpg") || fileName.endsWith("jpe") || fileName.endsWith("jpeg")) {
			return "image/jpg";
		} else if (fileName.endsWith("png")) {
			return "image/png";
		} else if (fileName.endsWith("pic")) {
			return "image/pict";
		} else if (fileName.endsWith("avi")) {
			return "video/x-msvideo";
		} else if (fileName.endsWith("mp4")) {
			return "video/mp4";
		} else if (fileName.endsWith("ogg")) {
			return "video/ogg";
		} else if (fileName.endsWith("webm")) {
			return "video/webm";
		} else if (fileName.endsWith("HTML") || fileName.endsWith("html")) {
			return "text/html";
		} else if (fileName.endsWith("DOCX") || fileName.endsWith("docx") || fileName.endsWith("DOC")
				|| fileName.endsWith("doc")) {
			return "application/msword";
		} else if (fileName.endsWith("XML") || fileName.endsWith("xml")) {
			return "text/xml";
		}
		return "image/jpeg";
	}

	/**
	 * 把Bucket设置成所有人可读
	 *
	 * @param client
	 *            OSSClient对象
	 * @param bucketName
	 *            Bucket名
	 * @throws OSSException
	 * @throws ClientException
	 */
	public void setBucketPublicReadable(OSSClient client, String bucketName)
			throws OSSException, ClientException {
		// 创建bucket
		client.createBucket(bucketName);
		// 设置bucket的访问权限， public-read-write权限
		client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
	}


}
